#include "fiber.h"
#include "scheduler.h"
#include <string>
#include <vector>

void run_in_fiber2()
{
    std::cout << "run_in_fiber2 begin" << std::endl;
    std::cout << "run_in_fiber2 end" << std::endl;
}

void run_in_fiber()
{
    std::cout << "run_in_fiber begin" << std::endl;

    Fiber::ptr fiber(new Fiber(run_in_fiber2));
    fiber->resume();

    std::cout << "run_in_fiber end" << std::endl;
}

int main(int argc, char *argv[])
{
    std::cout << "main begin" << std::endl;
    Fiber::GetThis();
    Fiber::ptr fiber(new Fiber(run_in_fiber));
    fiber->resume();

    std::cout << "main begin" << std::endl;
    return 0;
}

// 一个简单的协程调度器实现
class Scheduler
{
public:
    void scheduler(Fiber::ptr task)
    {
        m_tasks.push_back(task);
    }

    void run()
    {
        Fiber::ptr task;
        auto it = m_tasks.begin();

        while (it != m_tasks.end())
        {
            task = *it;
            m_tasks.erase(it++);
            task->resume();
        }
    }

private:
    std::vector<Fiber::ptr> m_tasks;
};

void test_fiber(int i)
{
    std::cout << "hello world" << i << std::endl;
}

int main()
{
    Fiber::GetThis();

    Scheduler sc;
    for (int i = 0; i < 10; i++)
    {
        Fiber::ptr fiber(new Fiber(std::bind(test_fiber, i)));
        sc.scheduler(fiber);
    }

    sc.run();
    return 0;
}

